//
//  myPostCell.m
//  唧歪
//
//  Created by ZC on 15/7/9.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "myPostCell.h"
#import "AppDelegate.h"
#import "ViewController.h"


#define resend1postURL @"https://app.jiwaipro.com:8888/index.php/JiWai/repost"//重新发送
#define resend2postURL @"https://app.jiwaipro.com:8888/index.php/JiWai/reid"//替换
#define integralURL  @"https://app.jiwaipro.com:8888/index.php/JiWai/postuser"  //积分
#define audioPostURL @"https://app.jiwaipro.com:8888/index.php/JiWai/audioPlay"  //语音帖子

@implementation myPostCell{
    AppDelegate *delegate;
    NSString *resendStr;
    NSString *resendStr1;
    CLLocationManager *locationManager;
    UIAlertView *_alert;
    UIAlertView *_alert1;
    NSDictionary *roud;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    NSString *integral;  //积分
    NSString *integralStr;
    NSMutableArray *audioPostArray;
    NSMutableArray *audioArray;
    NSString *palyAudioPath;
    NSString *audio_Path;
    UIImageView *img;
    AVAudioPlayer *player;
}

- (void)awakeFromNib {
    
    
    audioPostArray = [NSMutableArray array];
    audioArray = [NSMutableArray array];
    
    player = [[AVAudioPlayer alloc] init];
    
    //按钮设置成椭圆形
    [self.reSendButton.layer setMasksToBounds:YES];
    [self.reSendButton.layer setCornerRadius:5.0];
    
    delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    
        [self messageAudio];
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    
}
-(void)messageAudio{
    img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 2, 80, 30)];
    _wf = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 20, 20)];
    
    img.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(audioplay)];
    [img addGestureRecognizer:singleTap];//点击图片事件
    
    _wf.image = [UIImage imageNamed:@"音量.png"];
    _lab = [[UILabel alloc]initWithFrame:CGRectMake(img.bounds.size.width-30, 5, 30, 20)];
    _lab.text = @"''";
    _lab.textAlignment = NSTextAlignmentRight;
    img.backgroundColor = [UIColor colorWithRed:252/255.0 green:208/255.0 blue:30/255.0 alpha:1];
    CALayer * layer = [img layer];
    [layer setCornerRadius:8.0];
    layer.borderColor = [[UIColor grayColor] CGColor];
    layer.borderWidth = 1;
    //添加四个边阴影
    img.layer.shadowColor = [UIColor blackColor].CGColor;
    img.layer.shadowOffset = CGSizeMake(0, 0);
    img.layer.shadowOpacity = 0.5;
    img.layer.shadowRadius = 10.0;
    //给iamgeview添加阴影 < wbr > 和边框
    //添加两个边阴影
    img.layer.shadowColor = [UIColor blackColor].CGColor;
    img.layer.shadowOffset = CGSizeMake(4, 4);
    img.layer.shadowOpacity = 0.5;
    img.layer.shadowRadius = 2.0;
    [img addSubview:_wf];
    [img addSubview:_lab];
    [self.audioView addSubview:img];
}
#pragma mark - 定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    NSString *locstr1 = @"http://restapi.amap.com/v3/assistant/coordinate/convert?locations=";
    NSString *locstr2 = [NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude];
    NSString *locstr3 = @"&coordsys=gps&output=json&key=b1ba3d04de3c8efdc866712f66033064";
    NSString *locstr4 = [NSString stringWithFormat:@"%@%@%@",locstr1,locstr2,locstr3];
    NSURL *url=[NSURL URLWithString:locstr4];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSString *poststr =@"";
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        roud = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:roud waitUntilDone:YES];
        NSArray *strarray = [roud[@"locations"] componentsSeparatedByString:@","];
        _longitude = [strarray[0] doubleValue];
        _latitude = [strarray[1] doubleValue];
    }];
}
-(void)refreshData{
    
}
- (IBAction)ReSend:(id)sender {
    //开始定位
    [locationManager startUpdatingLocation];
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您确定要重新发表该帖子吗？"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    _alert = alert;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        NSString *poststr =[NSString stringWithFormat:@"user_id=%@",delegate.user_id];
        [self londingPath:resend1postURL Str:poststr];
    }
    if (buttonIndex==0&&alertView==_alert1) {
        //跳转到主页
        AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ViewController *vc = [sb instantiateViewControllerWithIdentifier:@"homeVC"];
        [tempAppDelegate.mainNavigationController pushViewController:vc animated:YES];
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"ya" ofType:@"wav"];
        if (path) {
            //注册声音到系统
            AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:path]),&shake_sound_male_id);
            AudioServicesPlaySystemSound(shake_sound_male_id);
            //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
        }
        
        AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    }
}

-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        resendStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:resendStr waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    NSDateFormatter *fomatter=[[NSDateFormatter alloc]init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowTime=[fomatter stringFromDate:[NSDate date]];
    NSString *poststr =[NSString stringWithFormat:@"message_id=%@&newmessage_id=%@&message_time=%@&message_longitude=%f&message_latitude=%f",self.messageID,resendStr,nowTime,_longitude,_latitude];
    [self londingPath1:resend2postURL Str1:poststr];

}
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        resendStr1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:resendStr1 waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender{
    if ([resendStr1 isEqualToString:@"0"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"帖子重新发送失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"帖子已经重新发送"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        _alert1 = alert;
        [alert show];
        
        // 帖子重新发表成功之后 积分数 - 5 之后上传数据库
        integral=[NSString stringWithFormat:@"%d",([delegate.appPersonArray[0][@"user_count"] intValue]-5)];
        NSString *poststr1 =[NSString stringWithFormat:@"user_id=%@&user_count=%d",delegate.user_id,[integral intValue]];
        [self londingPath2:resend2postURL Str2:poststr1];
    }
}
-(void)londingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        integralStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:integralStr waitUntilDone:YES];
    }];
}
-(void)refreshData2:(NSMutableArray *)sender{
}


-(void)loadAudioPath:(NSString *)path Str:(NSString *)str{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        audioPostArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshDataAudio:) withObject:audioPostArray waitUntilDone:YES];
    }];
}
-(void)refreshDataAudio:(NSMutableArray *)array{
    for(NSDictionary *dic in array){
        audio_Path = [NSString stringWithFormat:@"%@",dic[@"audio_path"]];
    }
    if (self.avPlay.playing) {
        [self.avPlay stop];
        [self.wf stopAnimating];
        return;
    }else{
        
        NSURL *url=[NSURL URLWithString:audio_Path];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.avPlay = [player initWithData:data error:nil];
        [self.avPlay prepareToPlay];
        [self.avPlay play];
        self.wf.animationImages = [NSArray arrayWithObjects:
                                           [UIImage imageNamed:@"音量.png"],
                                           [UIImage imageNamed:@"音量2.png"],
//                                           [UIImage imageNamed:@"播放特效3.png"],
                                   nil];
        self.wf.animationDuration = 1.0;
        self.wf.animationRepeatCount = 0;
        [self.wf startAnimating];
        self.avPlay.delegate = self;
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self.wf stopAnimating];
    
}
-(void)audioplay{

        NSString *str = [NSString stringWithFormat:@"message_id=%@",self.messageID];
        [self loadAudioPath:audioPostURL Str:str];

}
@end
